package com.example.chronicdisease.service;

import com.example.chronicdisease.dto.OrdersPageRequestDto;
import com.example.chronicdisease.dto.OrdersPageResponseDto;
import com.example.chronicdisease.mapper.OrdersMapper;
import com.example.chronicdisease.pojo.Orders;
import com.example.chronicdisease.pojo.Users;
import com.example.chronicdisease.response.ApiRestResponse;
import com.example.chronicdisease.response.ChronicDiseaseException;
import com.example.chronicdisease.response.ChronicDiseaseExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;

    @Override
    public ApiRestResponse InsertOrders(Orders orders) {

        ordersMapper.insertSelective(orders);
        Integer orderId = orders.getOrderId();
        return ApiRestResponse.success(orderId);
    }


    //用户预约体检订单列表
    @Override
    public List<Orders> getOrder(Orders orders) {
        List<Orders> ordersList = ordersMapper.getUserOrders(orders.getUserId());
        List<Orders> filteredOrdersList = new ArrayList<>();

        // 遍历订单列表
        for (Orders order : ordersList) {
            // 只处理状态不为 0 的订单
            if (order.getState() != 0) {
                Integer smId = order.getSmId();
                String smName = ordersMapper.getSetmealName(smId);
                order.setSmName(smName);
                filteredOrdersList.add(order); // 将符合条件的订单加入新列表
            }
        }

        return filteredOrdersList;
    }

    //医生体检报告分页列表
    @Override
    public OrdersPageResponseDto listOrders(OrdersPageRequestDto request) {
        OrdersPageResponseDto response = new OrdersPageResponseDto();

        //获取总行数
        int totalRow = ordersMapper.getOrdersCount(request);
        response.setTotalRow(totalRow);

        //如果总行数为0，那么直接返回
        if(totalRow == 0) {
            return response;
        }

        //计算总页数
        int totalPageNum = 0;
        if(totalRow%request.getMaxPageNum()==0) {
            totalPageNum = totalRow/request.getMaxPageNum();
        }else {
            totalPageNum = totalRow/request.getMaxPageNum()+1;
        }
        response.setTotalPageNum(totalPageNum);



        //计算上一页和下一页
        int pageNum = request.getPageNum();
        if(pageNum>1) {
            response.setPreNum(pageNum-1);
        }
        if(pageNum<totalPageNum) {
            response.setNextNum(pageNum+1);
        }

        //计算开始查询记录数
        request.setBeginNum((pageNum-1)*request.getMaxPageNum());
        //查询业务数据
        List<Orders> list = ordersMapper.listOrders(request);
        List<Orders> reportList = new ArrayList<>();

        // 遍历订单列表
        for (Orders order : list) {
            // 只处理状态不为 0 的订单
            if (order.getState() != 0) {
                Integer smId = order.getSmId();
                String smName = ordersMapper.getSetmealName(smId);
                order.setSmName(smName);

                Integer hpId = order.getSmId();
                String hpName = ordersMapper.getHospitalName(hpId);
                order.setHpName(hpName);

                String userId = order.getUserId();
                Users user = ordersMapper.getUser(userId);
                order.setUsers(user);

                reportList.add(order); // 将符合条件的订单加入新列表
            }
        }

        //给返回值填充余下的数据
        response.setPageNum(pageNum);
        response.setMaxPageNum(request.getMaxPageNum());
        response.setList(reportList);

        return response;
    }

    //取消预约
    @Override
    public ApiRestResponse<Object> cancelOrder(Integer orderId) {
        Orders order = ordersMapper.selectByPrimaryKey(orderId);

        Date orderDate = order.getOrderDate();
        LocalDate orderLocalDate = orderDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate today = LocalDate.now();

        if (orderLocalDate.isBefore(today) || ChronoUnit.DAYS.between(today, orderLocalDate) <= 2) {
            throw new ChronicDiseaseException(ChronicDiseaseExceptionEnum.ORDER_NO_CANCEL2);
        }

        ordersMapper.deleteByPrimaryKey(orderId);

        return ApiRestResponse.success();

    }

    //用户已体检订单列表
    @Override
    public List<Orders> getReport(Orders orders) {
        List<Orders> reportlist = ordersMapper.getUserOrders(orders.getUserId());
        List<Orders> List = new ArrayList<>();

        // 遍历订单列表
        for (Orders order : reportlist) {
            // 只处理状态为 2 的订单(已归档)
            if (order.getState() == 2) {

                Integer hpId = order.getSmId();
                String hpName = ordersMapper.getHospitalName(hpId);
                order.setHpName(hpName);

                List.add(order); // 将符合条件的订单加入新列表
            }

        }
        return List;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        System.out.println("这是ordersService.getOrdersById接收到的id"+orderId);
        Orders orders=ordersMapper.getOrdersById(orderId);
        System.out.println("这是ordersService.getOrdersById查询到的orders"+orders);
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public int updateOrdersState(Orders orders) {
        System.out.println("更新传值成功！");
        return ordersMapper.updateOrdersState(orders);
    }

}
